package com.atguigu.gulimall.cart.interceptor;

import com.atguigu.common.constant.AuthServerConstant;
import com.atguigu.common.vo.MemberRespVo;
import com.atguigu.gulimall.cart.constant.CartConstant;
import com.atguigu.gulimall.cart.vo.UserInfoTo;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.xml.bind.SchemaOutputResolver;
import java.util.UUID;

/**
 * 执行目标方法之前判断用户状态并封装传递给controller
 *
 */


public class CartInterceptor implements HandlerInterceptor{

    public static ThreadLocal<UserInfoTo> threadLocal = new ThreadLocal<>();

    //目标方法执行之前
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        HttpSession session = request.getSession();
        MemberRespVo member = (MemberRespVo) session.getAttribute(AuthServerConstant.LOGIN_USER);

        UserInfoTo userInfoTo = new UserInfoTo();

        if(member!=null){
            //用户登录，userInfoTo的id设置为正式用户的id
            userInfoTo.setUserId(member.getId());
        }


        Cookie[] cookies = request.getCookies();

        if(cookies!=null && cookies.length>0){

            for (Cookie cookie : cookies) {

                //user-key
                String name = cookie.getName();

                //如果有user-key，则为临时用户

                if(name.equals(CartConstant.TEMP_USER_COOKIE_NAME)){

                    //把user-key给到正式的用户
                    userInfoTo.setUserKey(cookie.getValue());
                    userInfoTo.setTempUser(true);
                }

            }
        }

        //如果没有临时用户一定分配一个临时用户
        if(StringUtils.isEmpty(userInfoTo.getUserKey())){

            //非正式用户，key设置为临时id
            String uuid = UUID.randomUUID().toString();
            userInfoTo.setUserKey(uuid);

        }


        System.out.println("userInfo的值是：" + userInfoTo);
        threadLocal.set(userInfoTo);
        return true;
    }

    /**
     * 业务执行之后
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {


        UserInfoTo userInfoTo = threadLocal.get();

        if(!userInfoTo.getTempUser()){

            //给浏览器返回一个user-key的cookie
            Cookie cookie = new Cookie(CartConstant.TEMP_USER_COOKIE_NAME,userInfoTo.getUserKey());
            cookie.setDomain("gulimall.com");
            cookie.setMaxAge(CartConstant.TEMP_USER_COOKIE_TIMEOUT);
            response.addCookie(cookie);
        }
    }
}
